package com.wd.home.activity


import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.CameraUpdateFactory
import com.amap.api.maps2d.MapView
import com.amap.api.maps2d.model.LatLng
import com.amap.api.maps2d.model.Marker
import com.amap.api.maps2d.model.MarkerOptions
import com.tencent.mm.opensdk.utils.Log
import com.wd.common.base.BaseActivity
import com.wd.common.viewmodel.MyViewModel
import com.wd.home.R
import com.wd.home.adapter.ChargeAdapter
import com.wd.home.callback.OnBack
import com.wd.home.databinding.ActivityChargeBinding
import java.net.URISyntaxException


class ChargeActivity : BaseActivity<ActivityChargeBinding,MyViewModel>() {
    private var latLng: LatLng?=null
    var aMap: AMap?=null
    val  viewmodel:MyViewModel by viewModels()
    var mMapView: MapView? = null
    private var adapter: ChargeAdapter?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //获取地图控件引用
        mMapView =  findViewById(R.id.ditu)
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView?.onCreate(savedInstanceState)
        //定位
        init()
        val callback=object :OnBack{
            override fun onClick(position: String, name: String) {
                aMap?.clear()
                val markerOptions = MarkerOptions()
                val split = position.split(",")
                latLng = LatLng(split[1].toDouble(),split[0].toDouble())
                move()
                markerOptions.position(latLng)
                markerOptions.title(name)
                aMap!!.addMarker(markerOptions)
            }
            override fun tomap(loader: String) {
                goGaodeMap(baseContext,22.618458,114.033342,"深圳北站")
            }
        }
        //突出定位
        move()
        viewmodel.nearChargeStation("40.052505,116.162364")
        viewmodel.nearChargeStation.observe(this) {
            try {
                it?.let {
                    adapter = ChargeAdapter(this,it,callback)
                    adapter.let {
                        binding.chargeRec.adapter = it
                        binding.chargeRec.layoutManager=LinearLayoutManager(this)
                        adapter!!.notifyDataSetChanged()
                    }
                }
            } catch (e:Exception) {
                e.printStackTrace()
            }
        }
    }
    /**
     * 判断手机中是否安装指定包名的软件
     * @param context
     * @param pkgname 包名
     */
    fun isInstallApk(context: Context, pkgname: String): Boolean {
        val packages = context.packageManager.getInstalledPackages(0)
        for (i in packages.indices) {
            val packageInfo = packages[i]
            return if (packageInfo.packageName == pkgname) {
                true
            } else {
                continue
            }
        }
        return false
    }
    /**
     * 跳转到高德地图
     * @param context
     * @param latitude 纬度
     * @param longtitude 经度
     * @param address 终点
     */
    private fun goGaodeMap(
        context: Context,
        latitude: Double,
        longtitude: Double,
        address: String
    ) {
        if (isInstallApk(context, "com.autonavi.minimap")) {
            try {
                val intent = Intent.getIntent(
                    "androidamap://navi?sourceApplication=&poiname=" + address + "&lat=" + latLng!!.latitude
                            + "&lon=" +  latLng!!.longitude + "&dev=0"
                )
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK )
                context.startActivity(intent)
            } catch (e: URISyntaxException) {
                Log.e("goError", e.message)
            }
        } else {
            Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_SHORT).show()
        }
    }
    override fun getViewBinding()=ActivityChargeBinding.inflate(layoutInflater)

    override fun initData() {

    }

    fun init(){
             aMap = mMapView?.getMap()!!
          latLng = LatLng(40.052505, 116.162364)
         val marker: Marker =
             aMap!!.addMarker(MarkerOptions().position(latLng).title("温泉").snippet("显龙山"))
     }
    override fun onDestroy() {
        super.onDestroy()
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView!!.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView!!.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView!!.onPause()
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView!!.onSaveInstanceState(outState)
    }

    fun move() {
        aMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f))
        aMap!!.invalidate() // 刷新地图
    }

}
